const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
//const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const index = require('./routes/index')
const users = require('./routes/users')


const cors = require('koa2-cors')//跨域访问
app.use(cors());

// error handler
onerror(app)

//middlewares
//app.use(bodyparser({
 // enableTypes: ['json', 'form', 'text']
//}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

//upload
const koaBody = require('koa-body')
app.use(koaBody({
  multipart: true,
  formidable: {
    maxFileSize: 100 * 1024 * 1024,//10M
    //  uploadDir:'upload/',
    //  onFileBegin:(name,file)=>{
    //    file.name = `${Date.now()}.${file.name}`
    //    file.path = `upload/${file.name}`
    //  }
  }
}))



app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  if (ctx.method == 'OPTIONS') {
    ctx.body = 200;
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Headers', 'Origin,Content-Type,Content-Length,Authorization,Accept,X-Requested-with,yourHeaderFeild');
    ctx.set('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  }
  else {
    await next();
  }
})



const mongo = require('./routes/mongo')
app.use(mongo.routes()).use(mongo.allowedMethods())

const upload = require('./routes/upload')
 app.use(upload.routes()).use(upload.allowedMethods())

const getFileList = require('./routes/getFileList')
app.use(getFileList.routes()).use(getFileList.allowedMethods())

const download = require('./routes/download')
app.use(download.routes()).use(download.allowedMethods())






app.listen(3001, () => {
  console.log('koa is listening in 3001')
})
module.exports = app;
